package com.mall.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.common.ServerResponse;
import com.mall.dao.MmallShippingMapper;
import com.mall.pojo.MmallShipping;
import com.mall.service.IShippingService;

@Service
public class ShippingServiceImpl implements IShippingService {
	
	@Autowired
	private MmallShippingMapper shippingMapper;
	
	@Override
	public ServerResponse insert(Integer userId, MmallShipping shipping) {
		
		shipping.setUserId(userId);
		int count = shippingMapper.insert(shipping);
		if(count == 0){
			return ServerResponse.createByErrorMessage("新建地址失败");
		}
		
		Map map = new HashMap();
		map.put("shippingId",shipping.getId() );
		return ServerResponse.createBySuccess("新建地址成功",map);
	}

	@Override
	public ServerResponse delete(Integer userId, Integer shippingId) {
		
		int count = shippingMapper.deleteByUserIdShippingId(userId,shippingId);
		if(count > 0){
			return ServerResponse.createBySuccessMessage("删除地址成功");
		}
		return ServerResponse.createByErrorMessage("删除地址失败");
		
	}

	@Override
	public ServerResponse update(Integer userId, MmallShipping shipping) {
		
		shipping.setUserId(userId);
		int count = shippingMapper.updateByUserIdandShipping(shipping);
		if(count > 0){
			return ServerResponse.createBySuccess("更新地址成功");
		}
		return ServerResponse.createByErrorMessage("更新地址失败");
	}

	@Override
	public ServerResponse selectByUserIdShippingId(Integer userId, Integer shippingId) {
		
		 MmallShipping shipping  = shippingMapper.selectByShippingIdUserId(userId,shippingId);
		 if(shipping == null){
			 return ServerResponse.createByErrorMessage("查不到该地址");
		 }
		return ServerResponse.createBySuccess(shipping);
	}

	@Override
	public ServerResponse<PageInfo> list(Integer userId, Integer pageNum, Integer pageSize) {
		
		//分页
		PageHelper.startPage(pageNum, pageSize);
		
		//查询
		List<MmallShipping> shippings = shippingMapper.selectByUserId(userId);
		
		//取分页结果
		PageInfo info = new PageInfo<>(shippings);
		
		
		return ServerResponse.createBySuccess(info);
	}
	
}

